package com.aga.app;

import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aga.app.domain.Rss.Channel.Item;
import com.aga.app.service.PeerFlyFeedFetcherService;

@Controller
@RequestMapping("/pf")
public class PeerflyAppService {

	@Autowired
	private PeerFlyFeedFetcherService service;
	ResourceBundle bundle = ResourceBundle.getBundle("peerCafe",Locale.ENGLISH);
	private final String POPF="popfeed";
	private final String ALLF="allfeed";
	
	
	
	@RequestMapping(value="/offers/getPopularFeed",method = RequestMethod.GET)
	public @ResponseBody List<Item> fetchPopularFeed(HttpServletRequest request){ 
		try{
			if(request.getSession().getAttribute(POPF)!=null) {
				System.out.println("Getting from Session");
					return ((List<Item>) request.getSession().getAttribute(POPF));
				}
			else{
				System.out.println("Getting from service");
				List<Item> data=service.getFeedUnmarshal(bundle.getString(POPF));
				request.getSession().setAttribute(POPF,data);
				return data;
			}
     	}catch(Exception e){
    		e.printStackTrace();
    	}
		return null; 
	}
	
	@RequestMapping(value="/offers/getAllFeed/{count}",method = RequestMethod.GET)
	public @ResponseBody List<Item> fetchAllFeed(@PathVariable String count, HttpServletRequest request){ 
		try{
			if(request.getSession().getAttribute(ALLF)!=null) {
				System.out.println("Getting from Session "+count);
					return getSubList(((List<Item>) request.getSession().getAttribute(ALLF)),count);
				}
			else{
				System.out.println("Getting from service "+count);
				List<Item> data=service.getFeedUnmarshal(bundle.getString(ALLF)+"?count=all");
				request.getSession().setAttribute(ALLF,data);
				return getSubList(data,count);
			}
     	}catch(Exception e){
    		e.printStackTrace();
    	}
		return null; 
	}
	
	@RequestMapping(value="/offers/getAllFeed",method = RequestMethod.GET)
	public @ResponseBody List<Item> fetchAllFeed(HttpServletRequest request){  
		return fetchAllFeed("10",request); 
	}

	private List<Item> getSubList(List<Item> list, String count) { 
		if(isInteger(count)){
			return list.subList(0, Integer.parseInt(count));
		}
		else
			return list;
		
	}

	private boolean isInteger(String count) { 
		try{
			Integer.parseInt(count);
			return true;
		}catch(Exception e){
			return false;	
		}
		
	}
}
